
from fastapi import FastAPI, Request
import socket
import winrm
 
app = FastAPI()
 
 
@app.get("/")
async def root():
    return {"message": "Hello World"}

@app.get("/api/winrmdownload")
async def info(request: Request):
    """
    通过winrm下载文件
    :return:
    """
    cecip = request.query_params["cecip"]
    cecusername = request.query_params["cecusername"]
    fileName = request.query_params["fileName"]
    try:
        win = winrm.Session(r'http://{0}:5985/wsman'.format(cecip),auth=(r'cec\administrator',r'cec-2023'), transport="ntlm")
        r= win.run_ps(r"$client=new-object System.Net.WebClient; $client.DownloadFile('http://10.10.10.3:9528/api/download?filename={0}&cecusername={1}', '\\fs0\个人云盘\{1}\{0}')".format(fileName, cecusername))
    except socket.gaierror as e:
        ip = None
        return {
        "result": False,
        }
    return {
        "result": True,
    }

@app.post("/api/winrmdownload")
async def infoPost(request: Request):
    """
    通过winrm下载文件
    :return:
    """
    form_data = await request.form()
    # cecip = form_data["cecip"]
    cecusername = form_data["cecusername"]
    fileName = form_data["fileName"]
    stauts = form_data["stauts"]
    cecip = "10.10.10.30"
    # cecip = "10.10.0.237"
    print(cecusername)
    print(fileName)
    print(stauts)
    try:
        win = winrm.Session(r'http://{0}:5985/wsman'.format(cecip),auth=(r'cec\administrator',r'cec-2023'), transport="ntlm")
        # win = winrm.Session(r'http://{0}:5985/wsman'.format(cecip),auth=(r'cec\15368002928',r'5112023wj@'), transport="ntlm")
        if stauts == "upload":
            r1 = win.run_ps(r"$client=new-object System.Net.WebClient; $client.DownloadFile('http://10.10.10.4:9529/api/download?filename={0}&cecusername={1}', 'D:\个人云盘\{1}\Downloads\{0}')".format(fileName, cecusername))
            # r1 = win.run_ps(r'wget "http://10.10.10.4:9529/api/download?filename=vscode setting.txt&cecusername=15368002928" -OutFile D:\个人云盘\15368002928\Downloads\wangjing2.txt')
            print(r1)
        # elif stauts == "alc":
            # # r1 =  win.run_ps(r"$ACL = Get-Acl -Path'D:\个人云盘\{1}\Downloads\{0}';$AccessRule = New-Object System.Security.AccessControl.FileSystemAccessRule('{1}.cec.cc', 'Read', 'Allow');$ACL.AddAccessRule($AccessRule);$ACL | Set-Acl -Path 'D:\个人云盘\{1}\Downloads\{0}'".format(fileName, cecusername))
            # # 文件路径
            # file_path = r"D:\个人云盘\{1}\Downloads\{0}".format(fileName, cecusername)
            # # 权限设置，例如："Everyone"用户设置为"修改"权限
            # access_rights = 'Everyone,MODIFY'
            # # 执行icacls命令来修改文件权限
            # command = f'icacls "{file_path}" /grant {access_rights}'
            # # 执行命令
            # r1 = win.run_cmd(command)
            # # 打印命令执行结果
        # # r2 =win.run_ps(r"$client=new-object System.Net.WebClient; $client.DownloadFile('http://10.10.10.3:9528/api/downloadend?filename={0}&cecusername={1}', 'C:\Users\{1}\{0}'; Move-Item -Path 'C:\Users\{1}\{0}' -Destination '\\fs0\个人云盘\{1}\{0}' -Force)".format(fileName, cecusername))
        # win.run_ps(r"New-Item -Path 'C:\Users\{0}\upload' -ItemType Directory".format(cecusername))
        # r1 = win.run_ps(r"$client=new-object System.Net.WebClient; $client.DownloadFile('http://10.10.10.3:9528/api/downloadend?filename={0}&cecusername={1}', 'C:\Users\{1}\{0}')".format(fileName, cecusername))
        # r1 = win.run_ps(r"$cred = Get-Credential -Credential Contoso\ServiceAccount; New-PSDrive -Persist -Name 'W' -Root '\\fs0\个人云盘' -Persist -PSProvider 'FileSystem' -Credential $credNet Use; $client=new-object System.Net.WebClient; $client.DownloadFile('http://10.10.10.3:9528/api/downloadend?filename={0}&cecusername={1}', '\\fs0\个人云盘\{1}\{0}') -Credential $credNet Use".format(fileName, cecusername))
        # # win.run_ps(r"move-item -Path 'C:\Users\{1}\upload\{0}' -Destination 'X:\test{0}' -force".format(fileName, cecusername))
        # win.run_ps(r"Start-Process 'explorer.exe' -ArgumentList '/select,C:\Users\{1}\upload\{0}'".format(fileName, cecusername))
        # win.run_ps(r"$Cred = New-Object System.Management.Automation.PsCredential('cec\15368002928', (ConvertTo-SecureString 'cec-123456' -AsPlainText -Force)); $client=new-object System.Net.WebClient; $client.DownloadFile('http://10.10.10.3:9528/api/downloadend?filename={0}&cecusername={1}', 'X:\Downloads\{0}') ".format(fileName, cecusername))
        # print(r1)
    except Exception as e:
        print(e)
        ip = None
        return {
        "result": True,
        }
    return {
        "result": True,
    }